cmake_minimum_required(VERSION 3.22)

project(qt5_opencv4_tutorial VERSION 0.1 LANGUAGES CXX)

set(CMAKE_AUTOUIC ON) # 自动处理 .ui 文件
set(CMAKE_AUTOMOC ON) # 自动处理 .cpp 文件中的 moc
set(CMAKE_AUTORCC ON) # 自动处理 .qrc 文件
set(CMAKE_CXX_STANDARD 17) # 设置 C++ 标准为 C++17
set(CMAKE_CXX_STANDARD_REQUIRED ON) # 设置 C++ 标准为必需项

# OpenCV
set(OpenCV_DIR "$ENV{HOME}/Lib/OpenCV_install/lib/cmake/opencv4") # 设置 OpenCV 的路径
find_package(OpenCV REQUIRED) # 查找并加载 OpenCV

# Qt
# 查找并加载 Qt 和 Qt 组件
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Widgets LinguistTools Multimedia)
# 根据 Qt 版本加载对应的组件
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets LinguistTools Multimedia) 

# 自动收集源文件，但排除 CMake 生成的文件
file(GLOB_RECURSE PROJECT_SOURCES 
  "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp"
  "${CMAKE_CURRENT_SOURCE_DIR}/*.h"
  "${CMAKE_CURRENT_SOURCE_DIR}/*.hpp"
  "${CMAKE_CURRENT_SOURCE_DIR}/*.ui"
)

list(FILTER PROJECT_SOURCES EXCLUDE REGEX ".*CMakeFiles.*") # 排除 CMake 生成的文件
list(FILTER PROJECT_SOURCES EXCLUDE REGEX ".*build.*") # 排除 build 目录下的文件

# 移除空文件
foreach(SOURCE ${PROJECT_SOURCES})
  if(EXISTS ${SOURCE})
    file(READ ${SOURCE} FILE_CONTENT)
    string(STRIP "${FILE_CONTENT}" FILE_CONTENT)
    if("${FILE_CONTENT}" STREQUAL "")
      list(REMOVE_ITEM PROJECT_SOURCES ${SOURCE}) # 移除空文件
    endif()
  else()
    list(REMOVE_ITEM PROJECT_SOURCES ${SOURCE}) # 移除不存在的文件
  endif()
endforeach()

# 打印源文件列表（用于调试）
# message(STATUS "Project sources: ${PROJECT_SOURCES}")

# 翻译文件
set(TS_FILES qt5_opencv4_tutorial_zh_CN.ts) # 设置翻译文件

# 添加可执行文件
if(${QT_VERSION_MAJOR} GREATER_EQUAL 6)
  qt_add_executable(${PROJECT_NAME}
    MANUAL_FINALIZATION
    ${PROJECT_SOURCES}
    ${TS_FILES}
  )
  qt_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES}) # 创建翻译文件
else()
  if(ANDROID)
    add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES} ${TS_FILES})
  else()
    add_executable(${PROJECT_NAME} ${PROJECT_SOURCES} ${TS_FILES})
  endif()
  qt5_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES}) # 创建翻译文件
endif()

# 设置包含目录
target_include_directories(${PROJECT_NAME} PRIVATE 
  ${CMAKE_CURRENT_SOURCE_DIR}
  ${CMAKE_CURRENT_SOURCE_DIR}/include
  ${CMAKE_CURRENT_SOURCE_DIR}/src/algo/face_detect_algo
  ${CMAKE_CURRENT_SOURCE_DIR}/src/algo/interface_settings
  ${CMAKE_CURRENT_SOURCE_DIR}/src/algo/algo_interface
  ${CMAKE_CURRENT_SOURCE_DIR}/src/ui/face_detect_view
  ${CMAKE_CURRENT_SOURCE_DIR}/src/ui/face_detect_thread
  ${CMAKE_CURRENT_BINARY_DIR}
)

# 链接库
target_link_libraries(${PROJECT_NAME} PRIVATE 
  Qt${QT_VERSION_MAJOR}::Widgets
  Qt${QT_VERSION_MAJOR}::Multimedia
  ${OpenCV_LIBS}
)

# 设置目标属性
set_target_properties(${PROJECT_NAME} PROPERTIES
  WIN32_EXECUTABLE TRUE
  MACOSX_BUNDLE TRUE
)

if(QT_VERSION_MAJOR EQUAL 6)
  qt_finalize_executable(${PROJECT_NAME})
endif()

# 安装
include(GNUInstallDirs)
install(TARGETS ${PROJECT_NAME}
  BUNDLE DESTINATION .
  LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
  RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
